package com.edu.rpc.service.impl;

import com.edu.rpc.service.WeatherService;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

@Service
public class WeatherServiceImpl implements WeatherService {
    // 1. 创建WebClient
    WebClient webClient = WebClient.create("https://jisutqybmf.market.alicloudapi.com/weather");

    @Override
    public Mono<String> getCities() {
        // 远程调用阿里云API


        // 2. 定义请求行为
        return webClient.get()
                // 添加请求路径/city
                .uri("/city")
                .accept(MediaType.APPLICATION_JSON)
                .header("Authorization", "APPCODE d512de6a02854b1bbf9508e1448f56f7")
                .retrieve()
                .bodyToMono(String.class);
    }

    /**
     * 根据城市名称查询天气
     */
    @Override
    public Mono<String> getWeatherByCityName(String city) {
        return webClient.get()
                // 添加参数：  city
                .uri(uriBuilder -> uriBuilder
                        .path("/query")
                        .queryParam("city", city)
                        .build())
                .accept(MediaType.APPLICATION_JSON)
                .header("Authorization", "APPCODE d512de6a02854b1bbf9508e1448f56f7")
                .retrieve()
                .bodyToMono(String.class);
    }

    /**
     * 根据城市ID查询天气
     * @param cityId 城市ID
     * @return 天气信息
     */
    @Override
    public Mono<String> getWeatherByCityId(String cityId) {
        return webClient.get()
                .uri(uriBuilder -> uriBuilder
                        .path("/query")
                        .queryParam("cityid", cityId)
                        .build())
                .accept(MediaType.APPLICATION_JSON)
                .header("Authorization", "APPCODE d512de6a02854b1bbf9508e1448f56f7")
                .retrieve()
                .bodyToMono(String.class);
    }
}
